package five;

public class Test {
    public static void main(String[] args) {
/*
//演示向上造型(多态)的第2点应用:
Master master = new Master();
Dog dog = new Dog("小黑",2,"黑");
Fish fish = new Fish("小金",1,"金");
Chick chick = new Chick("小花",3,"花");
master.feed(dog); //在传参的同时，系统自动做了向上造型
master.feed(fish);
master.feed(chick);
*/
//演示向上造型(多态)的第1点应用:
//Animal o = new Animal(); //抽象类不能被实例化
        Animal[] animals = new Animal[5]; //创建Animal数组对象
        animals[0] = new Dog("小黑", 2, "黑"); //向上造型
        animals[1] = new Dog("小白", 3, "白");
        animals[2] = new Fish("小金", 1, "金");
        animals[3] = new Fish("小花", 2, "花");
        animals[4] = new Chick("小灰", 3, "灰");
        for (int i = 0; i < animals.length; i++) { //遍历所有动物
            System.out.println(animals[i].name); //输出每个动物的名字
            animals[i].eat(); //每个动物吃饭  在使用多态后的父类引用变量调用方法时，会调用子类重写后的方法
            animals[i].drink(); //每个动物喝水  子类没有重写的方法，就直接使用父类中的方法
            if (animals[i] instanceof Dog) { // 若为Dog类型
                Dog dog = (Dog) animals[i];  // 将Animal类型强制准换为Dog类型
                dog.lookHome();              // 调用Dog类里面的lookHome方法，而Animal类里面没有lookHome方法，所以需要强制转换
            }
            if (animals[i] instanceof Chick) { //若为Chick类型
                Chick chick = (Chick) animals[i];
                chick.layEggs();
            }
            if (animals[i] instanceof Swim) { //若能游泳(实现Swim接口的)
                Swim s = (Swim) animals[i];
                s.swim();
            }
        }
        System.out.println("--------------------------");


        Master master = new Master();
        Dog dog = new Dog("小黑",2,"黑");
        Fish fish = new Fish("小金",1,"金");
        Chick chick = new Chick("小花",3,"花");
        master.feed(dog); //在传参的同时，系统自动做了向上造型
        master.feed(fish);
        master.feed(chick);

/*
Animal o = new Dog("小黑",2,"黑"); //向上造型
Dog d = (Dog)o; //引用o的对象，就是Doo类型
Swim s = (Swim)o; //引用o的对象，实现了Swim接口
//Fish f = (Fish)o; //运行时会发生ClassCastException类型转换
System.out.println(o instanceof Dog); //true
System.out.println(o instanceof Swim); //true
System.out.println(o instanceof Fish); //false
*/
    }
}
